<template>
  <el-dialog v-model="visible" :title="editData ? '编辑问答' : '新建问答'" width="70%">
    <el-form :model="form" label-width="80px">
      <el-form-item label="问题" required>
        <el-input v-model="form.question" placeholder="请输入问题"></el-input>
      </el-form-item>
      <el-form-item label="答案" required>
        <div class="editor-container">
          <!-- 这里可以集成富文本编辑器，如TinyMCE、Quill等 -->
          <el-input
            v-model="form.answer"
            type="textarea"
            :rows="10"
            placeholder="请输入答案"
          ></el-input>
          <div class="upload-area">
            <el-upload
              action="#"
              :before-upload="beforeUpload"
              :show-file-list="false"
            >
              <el-button type="primary">上传图片/视频</el-button>
            </el-upload>
          </div>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">提交</el-button>
        <el-button @click="visible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
// import { createQa, updateQa } from '@/api/knowledge'

const props = defineProps({
  modelValue: Boolean,
  editData: Object
})

// const emit = defineEmits(['update:modelValue', 'success'])

// const visible = computed({
//   get: () => props.modelValue,
//   set: (val) => emit('update:modelValue', val)
// })

const form = ref({
  question: '',
  answer: ''
})

watch(() => props.editData, (val) => {
  if (val) {
    form.value = { ...val }
  } else {
    form.value = {
      question: '',
      answer: ''
    }
  }
}, { immediate: true })

const beforeUpload = (file) => {
  const isImage = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type)
  const isVideo = ['video/mp4', 'video/webm', 'video/ogg'].includes(file.type)
  
  if (!isImage && !isVideo) {
    ElMessage.error('只能上传图片或视频文件')
    return false
  }
  
  // 处理文件上传逻辑
  // 上传成功后插入到编辑器内容中
  return false // 阻止自动上传
}

const submit = async () => {
  if (!form.value.question || !form.value.answer) {
    ElMessage.error('请填写问题和答案')
    return
  }
  
  try {
    if (props.editData) {
      // await updateQa(form.value)
      ElMessage.success('更新成功')
    } else {
      // await createQa(form.value)
      ElMessage.success('创建成功')
    }
    emit('success')
    visible.value = false
  } catch (e) {
    ElMessage.error('操作失败')
  }
}
</script>

<style scoped>
.editor-container {
  position: relative;
}

.upload-area {
  margin-top: 10px;
}
</style>